package com.example.listener;

import com.alibaba.fastjson.JSON;
import com.example.common.UserLogMessage;
import com.example.mapper.LogStorageMapper;
import com.example.pojo.OperationLog;
import jakarta.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RocketMQMessageListener(
        topic = "USER_LOG_TOPIC",
        selectorExpression = "*",
        consumerGroup = "logging-service-group"
)
public class UserLogListener implements RocketMQListener<UserLogMessage> {
    @Autowired
    private LogStorageMapper logStorageMapper;

    @Override
    @Transactional
    public void onMessage(UserLogMessage message) {
        log.info("[User Log Received] " + message);
        OperationLog operationLog = new OperationLog();
        operationLog.setUserId(message.getUserId());
        operationLog.setAction(message.getAction());
        operationLog.setIp(message.getIp());
        operationLog.setDetail(JSON.toJSONString(message.getExtraData()));

        log.info("[Log Saving] UserId: " + message.getUserId());
        logStorageMapper.insert(operationLog);
    }
}
